<template>
	<view class="pages-technician" :style="{background:pageColor}">
		<fixed :initHeight="configInfo">
			<block v-if="configInfo.coach_format !== 3">
				<uni-nav-bar :fixed="false" :shadow="false" :statusBar="true" :onlyLeft="true" :color="`#fff`"
					:backgroundColor="primaryColor">
					<view @tap.stop="$util.goUrl({url:`/userA/pages/choose/index?type=1`})"
						class="map-info flex-y-center" slot="left">
						<view class="flex-y-center c-base">
							<i class="iconfont iconjuli mr-sm"></i>
							<view class="map-text max-400 ellipsis">
								<block v-if="configInfo.user_update_location">{{location | handleAddrText}}
								</block>
								<block v-else>{{city_info | handleCityText}}</block>
							</view>
							<i class="iconfont icon-down"></i>
						</view>
					</view>
				</uni-nav-bar>
			</block>
			<block v-else>
				<!-- #ifndef H5 -->
				<uni-nav-bar :fixed="false" :shadow="false" :statusBar="true" :title="navTitle" color="#ffffff"
					:backgroundColor="primaryColor">
				</uni-nav-bar>
				<!-- #endif -->
			</block>

			<view class="fix-info choose rel"
				:style="{background:pageColor,height:configInfo.coach_format !== 3?'129rpx':'214rpx'}">
				<view class="space-top abs" :style="{background:primaryColor}" v-if="configInfo.coach_format !== 3">
				</view>
				<view class="search-info fill-base pt-lg pl-lg pr-lg pb-md abs"
					:style="{borderRadius:configInfo.coach_format==3?'0rpx':''}">
					<view class="pb-sm">
						<view @tap.stop="$util.goUrl({url:`/userA/pages/choose/index`})"
							class="map-info flex-y-center pb-lg" style="color:#7A7D7C"
							v-if="configInfo.coach_format==3">
							<view class="flex-y-center">
								<i class="iconfont iconjuli mr-sm" :style="{color:primaryColor}"></i>
								<view class="map-text ellipsis" style="max-width: 600rpx;">
									<block v-if="configInfo.user_update_location">{{location | handleAddrText}}</block>
									<block v-else>{{city_info | handleCityText}}</block>
								</view>
								<i class="iconfont icon-down"></i>
							</view>
						</view>
						<view class="flex-1">
							<search @input="toSearch" type="input" :keyword="param.coach_name" :padding="0" :radius="30"
								height="70rpx" backgroundColor="#F0F0F0"
								:placeholder="'请输入'+$t('action.attendantName')+'姓名'">
							</search>
						</view>
					</view>
				</view>
			</view>
		</fixed>


		<view class="ml-md mr-md"
			:class="[{'flex-warp':configInfo.coach_list_format === 2 || configInfo.plugAuth.industrytype === 2}]"
			v-if="list.data && list.data.length>0">
			<view class="mt-md"
				:class="[{'mr-md':(configInfo.coach_list_format == 2 || configInfo.plugAuth.industrytype === 2) && index%2==0}]"
				v-for="(item,index) in list.data" :key="index">
				<longbingbing-technician-list-item @comment="toShowPopup(index,'message')" @collect="toCollect(index)"
					@order="toOrder(index)" :info="item">
				</longbingbing-technician-list-item>
			</view>
		</view>


		<load-more :noMore="list.current_page>=list.last_page&&list.data.length>0&&location.lng" :loading="loading"
			v-if="loading">
		</load-more>

		<block v-if="!loading&&list.data.length<=0&&list.current_page==1">
			<abnor v-if="location.lat&&location.lng">
			</abnor>
			<block v-if="!location.lat&&!location.lng">
				<!-- #ifdef H5 -->
				<abnor type="NOT_LOCATION" :title="`暂无${$t('action.attendantName')}数据`"></abnor>
				<!-- #endif -->
				<!-- #ifndef H5 -->
				<abnor type="NOT_LOCATION" :title="`暂无${$t('action.attendantName')}数据`" @confirm="toOpenLocation"
					:button="[{ text: '开启定位' , type: 'confirm' }]" btnSize=""></abnor>
				<!-- #endif -->
			</block>
		</block>

		<longbingbing-technician-list-popup ref="technician_list_popup"></longbingbing-technician-list-popup>

		<uni-popup ref="choose_city_item" type="top" :custom="true" :zIndex="999">
			<!-- #ifdef H5 -->
			<view :style="{height:configInfo.user_update_location ? configInfo.navBarHeight + 8 + 'px' : '9px'}"></view>
			<!-- #endif -->
			<!-- #ifndef H5 -->
			<view :style="{height:(configInfo.navBarHeight + (configInfo.coach_format !== 3 ? -40 : 2))+ 'px'}">
			</view>
			<!-- #endif -->
			<view class="choose-city-popup rel">
				<image class="city-img" :src="`https://www.peikangbao.cn/admin/anmo/technician/no_city.png`"></image>
				<view class="text f-paragraph c-base abs">
					很抱歉,该城市未开通, 点击左上角切换其他城市下单服务
				</view>
				<view class="flex-between">
					<view></view>
					<view @tap.stop="$refs.choose_city_item.close()"
						class="item-btn flex-center f-paragraph c-title text-bold radius">知道了</view>
				</view>
			</view>
		</uni-popup>

		<view class="space-max-footer"></view>
		<fix-bottom-button @confirm="toBack" :text="[{type:'confirm',text:pageLen>1?`返回上页`:`返回首页`}]" bgColor="#fff">
		</fix-bottom-button>

		<!-- #ifdef MP-WEIXIN -->
		<user-privacy ref="user_privacy" :show="false"></user-privacy>
		<!-- #endif -->
		<!-- #ifdef APP-PLUS -->
		<longbingbing-app-check-auth type="location" ref="app_check_item"
			@confirm="toConfirmAppCheckAuth"></longbingbing-app-check-auth>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import longbingbingTechnicianListItem from "@/components/longbingbing-technician-list-item.vue"
	import longbingbingTechnicianListPopup from "@/components/longbingbing-technician-list-popup.vue"
	export default {
		components: {
			longbingbingTechnicianListItem,
			longbingbingTechnicianListPopup,
		},
		data() {
			return {
				isLoad: false,
				options: {},
				navTitle: '',
				param: {
					page: 1,
					ser_id: 0,
					coach_name: ''
				},
				list: {
					data: []
				},
				loading: true,
				lockTap: false,
				pageLen: 1,
				appMethod: ''
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			cityList: state => state.technician.cityList,
			technicianParam: state => state.technician.param,
			loginType: state => state.user.loginType,
		}),
		async onLoad(options) {
			console.log("====onLoad choose-technician")
			this.options = options
			// #ifndef H5
			this.$util.showLoading()
			// #endif
			await this.initIndex()
			let title = `选择${this.$t('action.attendantName')}`
			this.navTitle = title
			uni.setNavigationBarTitle({
				title
			})
			this.isLoad = true
		},
		async onShow() {
			if (!this.location.lat && this.locaRefuse) {
				this.toResetUtilLoca()
			}
		},
		onPullDownRefresh() {
			// #ifndef APP-PLUS
			uni.showNavigationBarLoading()
			// #endif 
			if (this.configInfo.realtime_location) {
				this.updateUserItem({
					key: 'changeAddr',
					val: false
				})
			}
			this.initRefresh();
			uni.stopPullDownRefresh()
		},
		onReachBottom() {
			if (this.list.current_page >= this.list.last_page || this.loading) return;
			this.param.page = this.param.page + 1;
			this.loading = true;
			this.getList();
		},
		watch: {
			locaRefuse(newval, oldval) {
				if (!newval) {
					this.toResetUtilLoca()
				}
			}
			// #ifndef H5
			,
			changeOnAddr(newval, oldval) {
				let {
					noloca,
					refresh
				} = this.noChangeLoca
				if (newval && noloca) {
					this.initUtilLocaData()
				}
			},
			noChangeLoca(newval, oldval) {
				setTimeout(() => {
					let {
						lat,
						lng,
						unix = 0
					} = this.changeOnAddr
					let {
						noloca,
						refresh
					} = this.noChangeLoca
					let cur_unix = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
					if (noloca && ((!lat && !lng) || !unix || (unix && (cur_unix - unix >= 1)))) {
						this.getUtilLocation()
					}
				}, 800)
			}
			// #endif
		},
		methods: {
			...mapActions(['getConfigInfo', 'getCityList']),
			...mapMutations(['updateUserItem', 'updateServiceItem', 'updateTechnicianItem', 'updateMapItem']),
			async initIndex(refresh = false) {
				if (!this.configInfo.id || refresh) {
					await this.getConfigInfo()
				}
				this.pageLen = getCurrentPages().length
				await this.isNotLoca()

				// #ifdef H5
				if (!refresh) {
					this.$jweixin.hideOptionMenu()
				}
				// #endif
			},
			initRefresh() {
				this.param.page = 1
				this.initIndex(true)
			},
			async toResetUtilLoca() {
				// #ifdef APP-PLUS
				let {
					lat: locaLat = 0
				} = this.location
				let {
					appCheckLocaStatus = null
				} = this
				if (!locaLat && appCheckLocaStatus == 1) {
					let {
						lng = 0,
							lat = 0
					} = await this.$util.getUtilLocation()
					if (!lat && !lng) return
					await this.initRefresh()
				}
				// #endif
			},
			toConfirmAppCheckAuth() {
				let {
					appMethod
				} = this
				this[appMethod]()
			},
			async toOpenLocation() {
				// #ifdef APP-PLUS
				if (plus.os.name == 'Android' && plus.navigator.checkPermission(
						'android.permission.ACCESS_FINE_LOCATION') ===
					'undetermined') {
					this.appMethod = 'toConfirmOpenLoca'
					this.$refs.app_check_item.open()
				} else {
					this.toConfirmOpenLoca()
				}
				// #endif
				// #ifndef APP-PLUS
				this.toConfirmOpenLoca()
				// #endif
			},
			async toConfirmOpenLoca() {
				// #ifdef MP-WEIXIN
				let privacyCheck = this.$refs.user_privacy.check()
				if (privacyCheck) {
					this.$refs.user_privacy.open()
					return
				}
				// #endif
				this.initRefresh()
			},
			toSearch(val) {
				this.param.page = 1
				this.param.coach_name = val
				this.getList()
			},
			// 选择地区 
			async toChooseLocation(init_city = 0) {
				this.updateUserItem({
					key: 'changeAddr',
					val: true
				})
				if (init_city) {
					let {
						lat,
						lng
					} = this.location
					await this.getCityList({
						lat,
						lng,
						change: 1
					})
				}
				this.param.page = 1
				await this.getList()
			},
			async isNotLoca() {
				let {
					location,
					locaRefuse,
					changeAddr
				} = this

				let {
					realtime_location = 0
				} = this.configInfo

				let {
					status: coach_status = 0,
					coach_position = 0
				} = this.userCoachStatus


				// #ifdef H5
				if (coach_position && coach_status == 2 && (location.lat && location.address != '暂未获取到位置信息')) {
					this.updateUserItem({
						key: 'isChangeCoachLoca',
						val: true
					})
				}
				// #endif


				// #ifdef APP-PLUS
				if (!locaRefuse && (!location.lat || (location.lat && location.address == '暂未获取到位置信息') || (
						realtime_location && !changeAddr))) {
					// #endif
					// #ifndef APP-PLUS
					if (!location.lat || (location.lat && location.address == '暂未获取到位置信息') || (
							realtime_location && !changeAddr)) {
						// #endif

						// #ifndef H5
						if (coach_position && coach_status == 2) {
							let {
								lat: change_lat = 0,
								lng: change_lng = 0,
								unix = 0
							} = this.changeOnAddr
							let cur_unix = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
							let noloca = change_lat && change_lng && (unix && (cur_unix - unix < 3)) ? false : true
							if (!noloca) {
								let loca = Object.assign({}, this.location, {
									lat: change_lat,
									lng: change_lng,
									is_util_loca: 1
								})
								this.updateUserItem({
									key: 'location',
									val: loca
								})
							}
							this.updateUserItem({
								key: 'noChangeLoca',
								val: {
									noloca
								}
							})
							if (this.noChangeLoca.noloca) return
							this.initUtilLocaData()
						} else {
							this.getUtilLocation()
						}
						this.updateServiceItem({
							key: 'pageActive',
							val: false
						})
						this.updateMapItem({
							key: 'pageActive',
							val: false
						})
						return
						// #endif

						// #ifdef H5
						await this.$util.getUtilLocation()
						this.updateServiceItem({
							key: 'pageActive',
							val: false
						})
						this.updateMapItem({
							key: 'pageActive',
							val: false
						})
						// #endif
					}
					this.initUtilLocaData()
				},
				async getUtilLocation() {
						await this.$util.getUtilLocation()
						this.initUtilLocaData()
					},
					async initUtilLocaData() {
							// #ifndef H5
							this.updateUserItem({
								key: 'noChangeLoca',
								val: {
									noloca: false
								}
							})
							// #endif


							let {
								city_id: cid = 0
							} = this.technicianParam
							let {
								id: city_info_id = 0
							} = this.city_info
							let param = this.$util.deepCopy(this.technicianParam)
							param.city_id = cid || city_info_id
							this.updateTechnicianItem({
								key: 'param',
								val: param
							})



							await this.getList(this.technicianParam.city_id && this.changeAddr ? false : true)

							let {
								changeAddr
							} = this

							let {
								realtime_location = 0
							} = this.configInfo
							let {
								lat = 0, lng = 0, is_util_loca = 0, isIp = true
							} = this.location
							if (is_util_loca || (realtime_location && !changeAddr)) {
								this.$util.getMapInfo(isIp, true, {}, changeAddr)
							}
						},
						async getList(refresh = false) {

								let {
									lat = 0, lng = 0, is_util_loca = 0, isIp = true
								} = this.location

								if (refresh || this.cityList.length == 0) {
									await this.getCityList({
										lat,
										lng,
										change: refresh ? 1 : this.technicianParam.city_id ? 0 : 1
									})
								}

								let {
									id: ser_id,
									store_id = 0
								} = this.options
								let {
									list: oldList,
									param,
									cityList,
								} = this

								let {
									city_id
								} = this.technicianParam

								let cityIndex = cityList.findIndex(item => {
									return item.id == city_id
								})

								if (cityIndex == -1) {
									this.loading = false
									this.$util.hideAll()
									this.list = {
										data: [],
										last_page: 1,
										current_page: 1
									}
									this.$refs.choose_city_item.open()
									return
								}
								param = Object.assign({}, param, {
									lat,
									lng,
									ser_id,
									city_id,
									store_id
								})

								let {
									coach_format = 1
								} = this.configInfo

								let methodModel = coach_format == 2 ? 'typeServiceCoachList' : 'serviceCoachList'

								let newList = await this.$api.service[methodModel](param)
								if (this.param.page == 1) {
									this.list = newList
								} else {
									newList.data = oldList.data.concat(newList.data)
									this.list = newList
								}
								this.loading = false
								this.$util.hideAll()
							},
							async toShowPopup(index, key) {
									this.$refs.technician_list_popup.toShowPopup(this.list.data[index], key)
								},
								async toCollect(index) {
										let {
											id,
											is_collect,
											collect_num
										} = this.list.data[index]
										let methodModel = is_collect ? 'delCollect' : 'addCollect'
										await this.$api.mine[methodModel]({
											coach_id: id
										})
										this.$util.showToast({
											title: is_collect ? '取消成功' : '收藏成功'
										})
										this.list.data[index].is_collect = is_collect == 1 ? 0 : 1
										this.list.data[index].collect_num = is_collect == 1 ? collect_num - 1 :
											collect_num + 1
									},
									// 预约
									async toOrder(index) {
										console.log(this.options, 'this.options')
											let {
												id: coach_id,
												is_work = 0
											} = this.list.data[index]
											// let {
											// 	id: service_id,
											// 	store_id = 0
											// } = this.options
											if (!is_work) return
											// let {
											// 	id: service_id = 0,
											// 	store_id = 0
											// } = this.options
											const store_id = 0
											const service_id = this.options.id
											if (this.lockTap) return;
											this.lockTap = true;
											let arr = []
											console.log(this.options.ids, 'this.option')
											if(this.options.ids){
												const list = JSON.parse(this.options.ids)
												console.log(list, 'list')
												arr = list.map(item => {
													return {
														coach_id: coach_id,
														num: item.num,
														is_top: 1,
														coach_service: 1,
														service_id: item.service_id
													}
												})
											}
											console.log(arr, 'arr')
											try {
												// await this.$api.order.addCar({
												// 	service_id,
												// 	coach_id,
												// 	num: 1,
												// 	is_top: 1,
												// 	coach_service: 1
												// })
												await this.$api.order.addCar(arr)
												this.lockTap = false
												console.log(this.options, 'this.options2')
												console.log(service_id, 'service_id')
												console.log(store_id, 'store_id')
												// return false
												let url =
													`/user/pages/order?id=${coach_id}&ser_id=${service_id}&store_id=${store_id}`
												this.$util.goUrl({
													url
												})
											} catch (e) {
												this.lockTap = false
											}
										},
										toBack() {
											let {
												pageLen
											} = this
											let url = pageLen > 1 ? 1 : `/pages/service`
											let openType = pageLen > 1 ? `navigateBack` : `reLaunch`
											this.$util.goUrl({
												url,
												openType
											})
										}
			},
			filters: {
				handleAddrText(val) {
					let text = `定位中...`
					if (val && val.lat) {
						let {
							address = '',
								address_info = ''
						} = val
						if (address || address_info) {
							if (!address_info) {
								let arr = address.split(' ')
								address_info = arr[arr.length - 1]
							}
							text = address_info
						}
					}
					return text
				},
				handleCityText(val) {
					let text = `未知城市`
					if (val && val.title) {
						text = val.title
					}
					return text
				}
			}
		}
</script>


<style lang="scss">
</style>